import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {Comment, Produce, ProduceService} from "../share/produce.service";

@Component({
  selector: 'app-produce-detail',
  templateUrl: './produce-detail.component.html',
  styleUrls: ['./produce-detail.component.css']
})
export class ProduceDetailComponent implements OnInit {
  isCommentArea:boolean=true;
  produce:Produce;
  comments:Comment[];
  newRating: number = 5;
  newComment:string='';
  constructor(
    //服务的注入方式只有一种  通过构造函数注入
    private routeInfo :ActivatedRoute,
    private produceService :ProduceService
  ) { }

  ngOnInit() {
    //http服务从服务器上获取的数据是异步的,如果说直接在页面上渲染的话 会报undefined 解决方式 在其前面加一个?号即可
    let produceId:number =this.routeInfo.snapshot.params["prodId"];

    this.produceService.getProduce(produceId).subscribe( function(data){
      console.log(data)
      this.produce=data
    }.bind(this));

    // console.log(this.produce)
    // debugger;
    this.produceService.getCommentsForProduceId(produceId).subscribe( comments=> this.comments=comments)
    // debugger;
    // console.log(this.comments)
  }
  addComment(){
    let comment = new Comment(0,this.produce.id,new Date().toISOString(),"somen",this.newRating,this.newComment);
    this.comments.unshift(comment);
    //reduce操作数据的API,一定要学会
    let sum = this.comments.reduce ((sum ,comment)=>sum +comment.rating,0);
    this.produce.rating=sum/this.comments.length;

    this.newComment=null;
    this.newRating=5;
    this.isCommentArea=true;
  }
}
